<template>
  <div class="login" id="login-app">
    <div class="login-box">
      <img src="../assets/login/login-l.png" alt="" />
      <div class="login-form">
        <el-form ref="emailFrom" :model="emailFrom" :rules="loginRules">
          <div class="login-form-title">
            <img src="../assets/login/logo.png" style="width:139px;height:42px;" alt="" />
          </div>
          <el-form-item prop="email">
            <el-input
              v-model="emailFrom.email"
              type="text"
              auto-complete="off"
              placeholder="账号"
              maxlength="20"
              prefix-icon="iconfont icon-user"
            />
          </el-form-item>

          <el-form-item prop="passwordHash">
            <el-input
              v-model="emailFrom.passwordHash"
               :type="showPassword ? 'text' : 'password'"
              auto-complete="off"
              placeholder="密码"
              maxlength="20"
              prefix-icon="iconfont icon-user"
            />
            <span  class="el-icon-view" @click="togglePassword"></span>
          </el-form-item>
          <el-form-item prop="newPassword">
            <el-input
              v-model="emailFrom.newPassword"
              :type="showPassword ? 'text' : 'password'"
              auto-complete="off"
              placeholder="确认密码"
              maxlength="20"
              prefix-icon="iconfont icon-user"
            />
            <span  class="el-icon-view" @click="togglePassword"></span>
          </el-form-item>
          <el-form-item prop="code" style="display: flex; align-items: center;">
            <el-input
              v-model="emailFrom.code"
              type="text"
              auto-complete="off"
              placeholder="验证码"
              maxlength="4"
              prefix-icon="iconfont icon-user"
              style="flex: 1; max-width: 100px; margin-right: 10px;"  
            />
            <el-button 
              :class="{ codeSend: true, disabled: isDisabled }"
              :disabled="isDisabled"
              @click="handleSendCode">
              {{ isDisabled ? `重新发送(${countdown}s)` : '发送验证码' }}
            </el-button>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              class="login-btn"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="register"
            >
              <span v-if="!loading">注册</span>
              <span v-else>注册...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {logregister,loginEmail } from '@/api/login';
export default {
  data() {
    return {
      emailFrom: {
        email: '',
        passwordHash: '',
        code:'',
        newPassword:'',
      },
      loading: false,
      showPassword: false, // 控制密码是否显示
      countdown: 120,
      isDisabled: false,
      timer: null
    };
  },
  computed: {
    loginRules() {
      const validateEmail = (rule, value, callback) => {
      // 邮箱正则表达式，用于基本的邮箱格式验证
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      // 检查输入是否为空
      if (!value || value.length < 1) {
          callback(new Error('请输入邮箱地址'));
      } else if (!emailRegex.test(value)) {
          // 检查邮箱格式是否正确
          callback(new Error('请输入有效的邮箱地址'));
      } else {
          callback(); // 验证成功
      }
    };
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码必须在6位以上'));
        } else {
          callback();
        }
      };
      const validateConfirmPassword = (rule, value, callback) => {
        if (value !== this.emailFrom.passwordHash) {
          callback(new Error('密码和确认密码不一致'));
        } else {
          callback();
        }
      };
      return {
        email: [{ validator: validateEmail, trigger: 'blur' }],
        passwordHash: [{ validator: validatePassword, trigger: 'blur' }],
        newPassword: [
          { validator: validatePassword, trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        // code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      };
    }
  },
  methods: {
    async handleSendCode() {
      //测试浏览器取用户信息
      const userInfoString = localStorage.getItem('userInfo');
      let userInfo;
      // 检查是否有数据
      if (userInfoString) {
        // 将 JSON 字符串解析为 JavaScript 对象
        userInfo = JSON.parse(userInfoString);
        // 现在你可以使用 userInfo 对象了
        console.log(userInfo);
      } else {
        console.log('没有找到 userInfo 数据');
      }

    if (this.isDisabled) return; // 如果按钮已经被禁用，则不执行任何操作
    this.startCountdown();
    try {
      const response = await loginEmail({
        //id:userInfo.id,
        email: this.emailFrom.email,
        passwordHash: this.emailFrom.passwordHash, // 应在前端处理密码加密
      });
      if (response.code === 200) { // 检查响应中的成功状态
        this.isSuccess = true;
        this.$message.success('发送验证码成功');
      } else if (response.code === 400){
        //时间
        this.isDisabled = true;
        this.countdown = parseInt(response.msg, 10);
        this.$message.error('验证码已存在');
      }else{
        this.isSuccess = false;
        this.$message.error('验证失败: ' + response.msg); // 确保错误消息从响应中获取
      }
    } catch (error) {
      this.isSuccess = false;
      this.$message.error('验证失败111: ' + error.message); // 捕获并显示错误消息
    } finally {
      this.loading = false;
    }
  },  
  //注册
  async register() {
    localStorage.removeItem('token');
    this.loading = true;
    try {
      const response = await logregister({
        email: this.emailFrom.email,
        passwordHash: this.emailFrom.passwordHash, // 应在前端处理密码加密
        code: this.emailFrom.code // 确保 code 是从数据中正确获取的
      });
      
      if (response.code === 200) { // 检查响应中的成功状态
        this.isSuccess = true;
        this.$message.success('注册成功');
        this.$router.push('/login'); // 假设注册成功后跳转到登录
      } else {
        this.isSuccess = false;
        this.$message.error('注册失败: ' + response.msg); // 确保错误消息从响应中获取
      }
    } catch (error) {
      this.isSuccess = false;
      this.$message.error('注册失败: ' + error.message); // 捕获并显示错误消息
    } finally {
      this.loading = false;
    }
  },
  startCountdown() {
    this.isDisabled = true;
    this.countdown = 120;
    this.timer = setInterval(() => {
      if (this.countdown <= 0) {
        clearInterval(this.timer);
        this.isDisabled = false;
        this.timer = null;
      } else {
        this.countdown -= 1;
      }
    }, 1000);
  },
  beforeDestroy() {
    // 清理计时器，避免内存泄漏
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  togglePassword() {
    this.showPassword = !this.showPassword;
  }
  }
};
</script>

<style scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 97.7vh; /* 使背景占满整个视口高度 */
  width: 99.2vw;  /* 使背景占满整个视口宽度 */
  background-color:#e0e6f8 ;
}
.login-box {
  width: 70%;
  height: 70%;
  border-radius: 8px;
  display: flex;
}

.login-box img {
  width: 60%;
  height: auto;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}
.login-form {
  background: #ffffff;
  width: 40%;
  border-radius: 0px 8px 8px 0px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login-form .el-form {
  width: 214px;
  height: 307px;
}
.login-form .el-form-item {
  margin-bottom: 20px;
}
.login-form .el-form-item.is-error .el-input__inner {
  border: 0 !important;
  border-bottom: 1px solid #fd7065 !important;
  background: #fff !important;
}
.login-form .input-icon {
  height: 32px;
  width: 18px;
  margin-left: -2px;
}
.login-form .el-input__inner {
  border: 0;
  border-bottom: 1px solid #e9e9e8;
  border-radius: 0;
  font-size: 14px;
  font-weight: 400;
  color: #333333;
  height: 32px;
  line-height: 32px;
}
.login-form .el-input__prefix {
  left: 0;
}
.login-form .el-input--prefix .el-input__inner {
  padding-left: 26px;
}
.login-form .el-input__inner::placeholder {
  color: #aeb5c4;
}
.login-form .el-form-item--medium .el-form-item__content {
  line-height: 32px;
}
.login-form .el-input--medium .el-input__icon {
  line-height: 32px;
}
.login-btn {
  border-radius: 17px;
  padding: 11px 20px !important;
  margin-top: 10px;
  font-weight: 500;
  font-size: 14px;
  border: 0;
  background-color: #0b8bed ;/*!important*/
}
.login-btn:hover,
.login-btn:focus {
  /* background: #FFC200; */
  /* color: #ffffff; */
}
.login-form-title {
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40px;
}
.login-form-title .title-label {
  font-weight: 500;
  font-size: 20px;
  color: #333333;
  margin-left: 10px;
}

.password-container {
  position: relative;
}

.el-icon-view {
  position: absolute;
  bottom: 13px; /* Adjust as needed */
  right: 5px;
  font-size: 12px;
  color: #242628;
  cursor: pointer;
}

.passwordr-link{
  position: absolute;
  bottom: -30px; /* Adjust as needed */
  left:0;
  font-size: 12px;
  color: #3794f7;
  cursor: pointer;
}

.register-link:hover {
  text-decoration: underline;
}

.passwordr-link:hover {
  text-decoration: underline;
}

.codeSend{
  position: absolute;
}
</style>
